package com.tarena.lbs.marketing.web.service;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.api.BasicApi;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.marketing.web.repository.ActivityRepository;
import com.tarena.lbs.pojo.attach.dto.AttachDTO;
import com.tarena.lbs.pojo.attach.param.PicUpdateParam;
import com.tarena.lbs.pojo.attach.query.AttachQuery;
import com.tarena.lbs.pojo.basic.dto.AdminDTO;
import com.tarena.lbs.pojo.marketing.param.ActivityParam;
import com.tarena.lbs.pojo.marketing.po.ActivityPO;
import com.tarena.lbs.pojo.marketing.query.ActivityQuery;
import com.tarena.lbs.pojo.marketing.vo.ActivityVO;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ActivityService {
    @Autowired
    private ActivityRepository activityRepository;
    @DubboReference
    private BasicApi basicApi;
    @DubboReference
    private AttachApi attachApi;
    public PageResult<ActivityVO> activityPage(ActivityQuery query) throws BusinessException {
        //1.解析认证
        UserPrinciple userPrinciple = LbsSecurityContenxt.getLoginToken();
        Asserts.isTrue(userPrinciple==null, new BusinessException("-2","用户认证解析失败"));
        //2.查询商家详情
        AdminDTO adminDto = basicApi.getAdminDetail(userPrinciple.getId());
        Asserts.isTrue(adminDto==null, new BusinessException("-2","商家信息不存在"));
        //3.查询活动分页
        query.setBusinessId(adminDto.getBusinessId());
        PageInfo<ActivityPO> pageInfo=activityRepository.activityPage(query);
        //4.封装分页数据返回
        PageResult<ActivityVO> voPage=new PageResult<>();
        voPage.setPageNo(pageInfo.getPageNum());
        voPage.setPageSize(pageInfo.getPageSize());
        voPage.setTotal(pageInfo.getTotal());
        List<ActivityVO> vos=null;
        if (CollectionUtils.isNotEmpty(pageInfo.getList())){
            vos=pageInfo.getList().stream().map(po->{
                ActivityVO vo=new ActivityVO();
                //拷贝
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPage.setObjects(vos);
        return voPage;
    }

    public void activitySave(ActivityParam param) throws BusinessException, ParseException {
        //1.解析认证
        UserPrinciple userPrinciple = LbsSecurityContenxt.getLoginToken();
        Asserts.isTrue(userPrinciple==null, new BusinessException("-2","用户认证解析失败"));
        //2.查询商家详情
        AdminDTO adminDto = basicApi.getAdminDetail(userPrinciple.getId());
        Asserts.isTrue(adminDto==null, new BusinessException("-2","商家信息不存在"));
        //3.补充活动poParam
        ActivityPO poParam=assembleActivityPo(param,adminDto.getBusinessId());
        //4.本地写入数据库
        activityRepository.save(poParam);
        //5.绑定图片 bizType=700
        bindPics(poParam);
    }

    private void bindPics(ActivityPO poParam) {
        //活动上传了多少张图片 就绑定多少张 每个图片id 拼接imgIds属性里
        String[] imgIds = poParam.getImgIds().split(",");
        List<PicUpdateParam> picParams = Arrays.stream(imgIds).map(imgId -> {
            PicUpdateParam param = new PicUpdateParam();
            param.setBusinessId(poParam.getId());
            param.setBusinessType(700);
            param.setId(Integer.valueOf(imgId));
            return param;
        }).collect(Collectors.toList());
        attachApi.batchUpdateBusiness(picParams);
    }

    private ActivityPO assembleActivityPo(ActivityParam param, Integer businessId) throws ParseException {
        //1.准备一个po
        ActivityPO poParam=new ActivityPO();
        //2.拷贝
        BeanUtils.copyProperties(param,poParam);
        //3.补充特殊属性 大部分跟优惠券类似
        poParam.setBusinessId(businessId);
        poParam.setStatus(0);//0待开始 1已发布 2已超时
        poParam.setEnableStatus(0);//0启用 1禁用
        //createAt updateAt
        poParam.setCreateAt(new Date());
        poParam.setUpdateAt(poParam.getCreateAt());
        //时间段 start end
        poParam.setStartDate(DateUtils.parseDate(param.getStartDate(),"yyyy-MM-dd HH:mm:ss"));
        poParam.setEndDate(DateUtils.parseDate(param.getEndDate(),"yyyy-MM-dd HH:mm:ss"));
        //奖励类型 数据库 非空处理
        poParam.setRewardType(1);
        return poParam;
    }

    public boolean isTargetConsumer(Integer userId, Integer activityId) {
        //1.读取活动详情 获取目标人群的id
        ActivityPO po=activityRepository.getActivityById(activityId);
        Integer targetId = Integer.valueOf(po.getTargetCustomer());
        List<Integer> userGroupIds=null;
        //2.远程调用basic 获取该用户 绑定的所有用户人群 一个用户绑定了n个标签 标签绑定了n人群
        basicApi.getUserGroups(userId);
        //所以一个用户可以查询人群数量也是n
        if (CollectionUtils.isNotEmpty(userGroupIds)){
            return userGroupIds.contains(targetId);
        }else{
            return false;
        }
    }

    //day13 PM 01 查询活动详情
    public ActivityVO activityDetail(Integer id) throws BusinessException {
        //1.先查数据库 activityPO
        ActivityPO activityPO = activityRepository.getActivityById(id);
        Asserts.isTrue(activityPO==null,new BusinessException("-2","活动不存在"));
        //2.查询绑定的图片数据 使用的条件就是当前活动的bizId bizType
        List<String> picUrls=getPicUrls(activityPO);
        //3.po 图片返回数据 封装完整的ActivityVO
        ActivityVO vo=new ActivityVO();
        BeanUtils.copyProperties(activityPO,vo);
        if (CollectionUtils.isNotEmpty(picUrls)){
            vo.setImgPics(picUrls);
        }
        return vo;
    }
    //day13 PM 01 查询活动详情
    @Value("${url-prefix}")
    private String urlPrefix;
    private List<String> getPicUrls(ActivityPO activityPO) {
        AttachQuery query=new AttachQuery();
        query.setBusinessType(700);
        query.setBusinessId(activityPO.getId());
        List<AttachDTO> attachDTOS = attachApi.getAttachInfoByParam(query);
        //每个图片查询 元素对象 都有该图片fileUuid 只要循环遍历将fileUuid拼接当前环境url前缀
        List<String> urls=null;
        if (CollectionUtils.isNotEmpty(attachDTOS)){
            urls=attachDTOS.stream().map(dto->{
                String urlPrefix="http://localhost:9081/static/";
                return urlPrefix+dto.getFileUuid();
            }).collect(Collectors.toList());
        }
        return urls;
    }
}
